<template>
  <!-- 物资入库 -->
  <div>
    <el-form
      ref="form"
      :model="form"
      :inline="true"
      :rules="rules"
      label-position="left"
      class="durg_form"
      @submit.native.prevent="onSubmit"
    >
      <label class="durg_title">编辑入库</label>
      <el-form-item prop="sendGoodsDate">
        <el-date-picker
          v-model="form.sendGoodsDate"
          type="date"
          :editable="true"
          value-format="yyyy-MM-dd"
          placeholder="发货日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item prop="putInStorageDate">
        <el-date-picker
          v-model="form.putInStorageDate"
          type="date"
          :editable="true"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          placeholder="入库日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item prop="inOutWay">
        <el-select v-model="form.inOutWay" value-key="id" placeholder="入库方式">
          <el-option v-for="item in wayList" :key="item.id" :label="item.desc" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          placeholder="供应商："
          filterable
          :filter-method="getSupplier"
          clearable
          v-model="form.supplierId"
          value-key="id"
        >
          <el-option
            v-for="(item,index) in supplierList"
            :key="index"
            :value="item.id"
            :label="item.supplierName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="form.remark"></el-input>
      </el-form-item>
      <el-button v-show="false" :loading="btnLoading" native-type="submit">提交</el-button>
    </el-form>
    <edit
      v-model="dialogEdit"
      v-if="dialogEdit"
      :totalMoney="form.totalMoney"
      :itemList="medicalStockItem"
      @getTotal="getTotal"
    ></edit>
    <el-row>
      <el-col :span="24">
        <el-button @click="addItem()" type="text">
          <i class="el-icon-plus"></i>
          添加
        </el-button>
      </el-col>
    </el-row>
    <br />
    <span slot="footer">
      <el-button type="primary" :loading="btnLoading" @click="onSubmit(1)">保 存</el-button>
      <el-button type="promary" @click="onSubmit(2)">保 存 并 审 核</el-button>
      <el-button @click="onClose">取消</el-button>
    </span>
  </div>
</template>
<script>
import Valid from "@/_js/validate.js";
export default {
  data() {
    return {
      btnLoading: false,
      form: {
        id: "",
        hpId: "",
        type: 1,
        deptId: "",
        receiveId: "",
        stockCode: "",
        inOutWay: "",
        sendGoodsDate: "",
        putInStorageDate: "",
        memberId: "",
        saveType: 1,
        remark: "",
        supplierId: "",
        status: 0,
        totalMoney: 0,
        source: 2 //1药品  2物资
      },
      medicalStockItem: [
        {
          source: 2, //来源
          durg: "",
          sourceName: "", //来源物品名
          sourceId: "", //来源id
          lotNumber: "", //批号
          effectiveTime: "", //有效期
          count: 0, //增减制剂数量
          packUnit: "", //增减包装单位
          purchasePrice: 0, //进价
          purchaseMoney: 0, //进价金额
          remark: "", //描述
          retailPrice: "", //零售价
          costPrice: "", //成本价
          show: false,
          invoiceNumber:'',
          acceptanceConclusion: 1 //验收结论
        }
      ],
      pickerOptions: {
        disabledDate: time => {
          return time.getTime() > Date.now();
        }
      },
      supplierList: [],
      wayList: [],
      rules: {
        sendGoodsDate: [
          { required: true, message: "此项必选", trigger: "change" }
        ],
        putInStorageDate: [
          { required: true, message: "此项必选", trigger: "change" }
        ],
        inOutWay: [{ required: true, message: "此项必选", trigger: "change" }]
      },
      durg_id: 0,
      dialogEdit: true,
      curItem: {}
    };
  },
  mounted() {
    let th = this;
    th.verifyUrlAttack(th.$route.query).then(() => {
      th.durg_id = th.jieMi(th.$route.query.id);
      th.getBasicData();
      th.onOpen();
      th.getSupplier();
    });
  },
  methods: {
    onSubmit(type) {
      let th = this;
      let j = {
        medicalStock: "",
        medicalStockItem: ""
      };
      th.form.memberId = th.jieMi(th.adminUser.memberId);
      th.form.saveType = type;
      let add = function() {
        th.btnLoading = true;
        th.$api.addMedicalStockV2(j).then(res => {
          if (res.executed) {
            th.$message.success("保存成功");
            th.$emit("success");
            th.onClose();
          } else {
            th.$message.error(res.message);
          }
        });
        th.btnLoading = false;
      };
      let update = function() {
        th.btnLoading = true;
        th.$api.updateMedicalStockV2(j).then(res => {
          if (res.executed) {
            th.$message.success("保存成功");
            //获取对应的科室名称
            th.$emit("success");
            th.onClose();
          } else {
            th.$message.error(res.message);
          }
        });
        th.btnLoading = false;
      };
      th.$refs["form"].validate(v => {
        if (v) {
          th.form.hpId = th.adminUser.hpId;
          th.form.memberId = th.adminUser.memberId;
          let list = th.medicalStockItem;
          let isB = true;
          list.map((item, index) => {
            if (item.sourceName != "" && item.sourceId != "") {
              if (item.count < 1) {
                th.$message.error("数量不能小于0！");
                isB = false;
              }
              if (item.lotNumber == "") {
                th.$message.error("请输入批号");
                isB = false;
              }
              if (item.effectiveTime == "") {
                th.$message.error("有效期不能为空！");
                isB = false;
              }
              return item;
            } else {
              list.splice(index, 1);
            }
          });
          // for(let i=0;i<list.length;i++){
          //   if(list[i].count<1){
          //     th.$message.error("数量不能小于0！");
          //     isB=false
          //     break;
          //   }
          //   if(list[i].effectiveTime==''){
          //     th.$message.error("有效期不能为空！");
          //     isB=false
          //     break;
          //   }
          // }
          if (isB == false) {
            return false;
          }
          j.medicalStock = JSON.stringify(th.form);
          j.medicalStockItem = JSON.stringify(list);
          if (th.durg_id != 0) {
            update();
          } else {
            add();
          }
        }
      });
    },
    onOpen() {
      let th = this;
      th.$nextTick(function() {
        if (th.durg_id != 0) {
          th.$api.findMedicalStockByIdV2({ id: th.durg_id }).then(res => {
            if (res.executed) {
              th.form = Object.assign(th.form, res.data.medicalStockInfo);
              let list = [];
              let sum = 0;
              let d = res.data.itemDtoList;
              for (let i = 0; i < d.length; i++) {
                let arr = { show: true };
                arr = Object.assign(arr, d[i]);
                sum += Number(d[i].purchaseMoney);
                list.push(arr);
              }
              th.form.totalMoney = sum;
              th.medicalStockItem = list;
            }
          });
        } else {
          th.form.putInStorageDate = th.getNewDate();
        }
      });
    },
    getSupplier(query) {
      let th = this;
      th.$api
        .findHpSupplierAll({ pageNum: 1, pageSize: 100, supplierName: query })
        .then(res => {
          if (res.executed) {
            th.supplierList = res.dataBody.list;
          }
        });
    },
    onClose() {
      let th = this;
      th.$refs["form"].resetFields();
      th.$router.push({
        path: "/page/suppliesIndex"
      });
    },
    //获取通用配置
    getBasicData() {
      let th = this;
      th.getCommonConfigByKey("入库方式").then(res => {
        th.wayList = res;
      });
      th.$api.findHpSupplierAll({ pageNum: 1, pageSize: 1000 }).then(res => {
        if (res.executed) {
          th.supplierList = res.dataBody.list;
        }
      });
    },
    addItem() {
      let th = this;
      let json = {
        source: 2, //来源
        durg: "",
        sourceName: "", //来源物品名
        sourceId: "", //来源id
        lotNumber: "", //批号
        effectiveTime: "", //有效期
        count: 0, //增减制剂数量
        packUnit: "", //增减包装单位
        purchasePrice: 0, //进价
        purchaseMoney: 0, //进价金额
        remark: "", //描述
        retailPrice: "", //零售价
        costPrice: "", //成本价
        show: false,
        invoiceNumber:'',
        acceptanceConclusion: 1 //验收结论
      };
      th.medicalStockItem.push(json);
    },
    getTotal(item) {
      let th = this;
      th.form.totalMoney = item;
    }
  },
  components: {
    edit: () => import("../_childcom/editPut")
  }
};
</script>
<style lang="scss" scoped>
.durg_title {
  display: inline-block;
  width: 100%;
  font-size: 16px;
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
  margin-bottom: 10px;
}
.durg_form {
  .el-input,
  .el-select {
    width: 90%;
  }
  .el-form-item__label {
    padding-bottom: 0;
  }
  .one_dose_select {
    width: 30%;
    position: absolute;
    right: 28px;
  }
}
</style>
